package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type question struct {
	iQuestion store.IQuestion
}

var Question = &question{
	iQuestion: mysql.Question,
}

func init() {
	Register(Question)
}

func (a *question) init() func() {
	return func() {}
}

// Create
func (a *question) Create(ctx context.Context, in *model.QuestionCreateRequest) error {
	var (
		err error
	)
	c := buildQuestion(in)
	_, err = a.iQuestion.Create(ctx, c)
	return err
}

// Update
func (a *question) Update(ctx context.Context, in *model.QuestionUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.Title != nil {
		dict["title"] = in.Title
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.AnswerId != nil {
		dict["answer_id"] = in.AnswerId
	}

	if in.LevelId != nil {
		dict["level_id"] = in.LevelId
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	if in.Image != nil {
		dict["image"] = in.Image
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iQuestion.Update(ctx, in.Id, dict)
}

// Delete
func (a *question) Delete(ctx context.Context, in *model.QuestionDeleteRequest) error {
	return a.iQuestion.Delete(ctx, in)
}

// List
func (a *question) List(ctx context.Context, in *model.QuestionListRequest) (*model.QuestionListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Question
		out   = &model.QuestionListResponse{}
	)

	if total, list, err = a.iQuestion.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.QuestionsEntityToDto(list)

	return out, nil
}

// Find
func (a *question) Find(ctx context.Context, in *model.QuestionInfoRequest) (*model.QuestionInfo, error) {
	var (
		err  error
		data *entity.Question
		out  = &model.QuestionInfo{}
	)

	if data, err = a.iQuestion.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.QuestionEntityToDto(data)
	return out, nil
}

// buildQuestion build entity
func buildQuestion(in *model.QuestionCreateRequest) *entity.Question {

	ety := &entity.Question{}

	ety.Title = in.Title

	ety.Type = in.Type

	ety.Image = in.Image

	ety.AnswerId = in.AnswerId

	ety.LevelId = in.LevelId

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
